<script setup lang="ts">
import {
  addCategory,
  deleteCategory,
  getCategoryList,
  updateCategory
} from '@/services/category'
import type { Category } from '@/types/category'
import { Edit, Delete } from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormItemRule,
  type FormRules
} from 'element-plus'
import { onMounted, ref } from 'vue'

onMounted(() => {
  loadCategoryList()
})

const categoryList = ref<Category[]>([])
const loadCategoryList = async () => {
  const res = await getCategoryList()
  categoryList.value = res.data
}

// -------------------添加分类------------------------------
// 控制添加分类弹窗
const dialogVisible = ref(false)
// 添加分类数据模型
type CategoryModel = {
  categoryName: string
  categoryAlias: string
  id?: number
}
const categoryModel = ref<CategoryModel>({
  categoryName: '',
  categoryAlias: ''
})
// 添加分类表单校验
const categoryName: FormItemRule[] = [
  { required: true, message: '请输入分类名称', trigger: 'blur' }
]
const categoryAlias: FormItemRule[] = [
  { required: true, message: '请输入分类别名', trigger: 'blur' }
]
const rules: FormRules<CategoryModel> = {
  categoryName,
  categoryAlias
}
// 添加文章分类
const formRef = ref<FormInstance>()
const close = () => {
  dialogVisible.value = false
  categoryModel.value = {
    categoryName: '',
    categoryAlias: ''
  }
}
const add = async () => {
  // 校验
  if (!formRef.value) return
  await formRef.value.validate()
  // 发请求
  await addCategory(
    categoryModel.value.categoryName,
    categoryModel.value.categoryAlias
  )
  // 请求成功
  ElMessage.success('添加成功')
  // 重新加载列表
  loadCategoryList()
  close()
}
// -------------------修改文章分类------------------------------
// 弹窗标题
const title = ref('')
// 编辑文章分类
const openUpdate = async (row: Category) => {
  dialogVisible.value = true
  title.value = '编辑分类'
  // 数据回显
  categoryModel.value.categoryName = row.categoryName
  categoryModel.value.categoryAlias = row.categoryAlias
  categoryModel.value.id = row.id
}
const update = async () => {
  // 校验
  if (!formRef.value) return
  await formRef.value.validate()
  // 发请求
  if (!categoryModel.value.id) return ElMessage.error('参数缺失')
  await updateCategory(
    categoryModel.value.id,
    categoryModel.value.categoryName,
    categoryModel.value.categoryAlias
  )
  // 请求成功
  ElMessage.success('编辑成功')
  // 重新加载列表
  loadCategoryList()
  close()
}
// -------------------删除文章分类------------------------------
const del = async (id: number) => {
  try {
    // 是否确定删除
    await ElMessageBox.confirm('确定删除吗?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发送请求
    await deleteCategory(id)
    // 请求成功
    ElMessage.success('删除成功')
    // 重新加载列表
    loadCategoryList()
  } catch (error) {
    ElMessage.info('取消删除')
  }
}
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文章分类</span>
        <div class="extra">
          <el-button
            @click="
              () => {
                dialogVisible = true
                title = '添加分类'
              }
            "
            type="primary"
          >
            添加分类
          </el-button>
        </div>
      </div>
    </template>
    <el-table :data="categoryList" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"> </el-table-column>
      <el-table-column label="分类名称" prop="categoryName"></el-table-column>
      <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            @click="openUpdate(row)"
            :icon="Edit"
            circle
            plain
            type="primary"
          ></el-button>
          <el-button
            @click="del(row.id)"
            :icon="Delete"
            circle
            plain
            type="danger"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </el-card>
  <!-- 添加分类弹窗 -->
  <el-dialog v-model="dialogVisible" :title="title" width="30%">
    <el-form
      ref="formRef"
      :model="categoryModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="categoryModel.categoryName"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="categoryAlias">
        <el-input
          v-model="categoryModel.categoryAlias"
          minlength="1"
          maxlength="15"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close"> 取消 </el-button>
        <el-button
          type="primary"
          @click="title === '添加分类' ? add() : update()"
        >
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
